package com.liyuxiang.yygh.sms.controller;

import com.liyuxiang.yygh.common.result.Result;
import com.liyuxiang.yygh.sms.service.SmsService;
import com.liyuxiang.yygh.sms.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
public class SmsApiController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/send/{phone}")
    public Result sendCode(@PathVariable("phone") String phone) {
        String code = (String) redisTemplate.opsForValue().get("sms-" + phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        code = RandomUtil.getSixBitRandom();
        boolean isSend = smsService.send(phone, code);
        if (isSend) {
            redisTemplate.opsForValue().set("sms-" + phone, code.replace("\"", ""), 2, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }
    }
}
